import init, { gotoms } from './bootstraps.js';
import {req} from './req.js';

let headers = {'User-Agent': 'okhttp/3.10.0'};

async function request(reqUrl, header, data, postType, tobase64) {
    try {
        let optObj = {
            headers: header || headers,
            method: postType ? 'post' : 'get',
            data: postType ? data : undefined,
            postType: postType || undefined,
            timeout: 5000,
        };
        if(tobase64){
            optObj.buffer = 2;
        }
        let res = await req(reqUrl, optObj);
        return res.content;
    } catch (e) {
        throw new Error();
    }
}

async function mymiss(fileUrl) {
    await init();
    try {

        const response = await request(fileUrl,undefined,undefined,undefined,'tobase64');

        // if (!response.ok) {
        //     throw new Error("Failed to fetch the mymiss file.");
        // }
        // const encryptedArrayBuffer = await response.arrayBuffer();
        // const encryptedArray = new Uint8Array(encryptedArrayBuffer);
        let encryptedArray = base64ToUint8Array(response);

        const decrypted = gotoms(encryptedArray)
        return decrypted;

    } catch (error) {
        console.error("Error during decryption:", error);
        return null;
    }
}

function base64ToUint8Array(base64String) {
    const cleanedBase64 = base64String.replace(/^data:.*;base64,/, '');
    const buffer = Buffer.from(cleanedBase64, 'base64');
    return new Uint8Array(buffer);
}

let dat = await mymiss('https://play.gotomymv.life/ws/9a893cb1753037769/58Njg3Y2NhZTU2NTZiMSQzMjE1JDEkMTc1MzAwODg2OQ687ccae5656af.svg')
console.log(dat)